// import express from 'express'
// import mongoose from 'mongoose'
const express =  require('express')
const mongoose = require('mongoose')

const app = express()

app.get('/', (req, res) => {
    res.send(`
        DB_URL = 'mongodb://127.0.0.1:27017/boss'
    `)
})

// database CRUD
// init
const DB_URL = 'mongodb://127.0.0.1:27017/boss'
mongoose.connect(DB_URL)
mongoose.useNewUrlParser = true
mongoose.useUnifiedTopology = true
// 主要为了callback
mongoose.connection.on('connected', d => {
    console.log('mongoose connect success')
})
const User = mongoose.model('user', new mongoose.Schema({
    name: {type:String, require: true},
    user: {type:String, require: false},
    age: {type:Number, require: true}
}))
// C
/*
User.create([{
        user: 'zhao111',
        name: 'zhaoxiaoyang',
        age: 33
    },
    {
        user: 'li222',
        name: 'lishiyinga',
        age: 22
    }
], (err, doc) => {
    console.log(!err ? doc : err)
})
*/

// U
User.update({user:'zhaoguangzhou'}, {'$set':{age:38}}, (err, doc) => {
    console.log(!err ? doc : err)
})
// D
User.remove({age:18}, (err, doc) => {
    console.log(!err ? doc : err)
})


app.get('/data', (req, res) => {
    User.find({}, (err, doc) => {
    // User.findOne({user:'lishiying'}, (err, doc) => {
    // User.find({user:'lishiying'}, (err, doc) => {
        res.json(doc)
    })
    // res.json({a:1,b:2,c:3})
})

app.listen(9093, a => {
    console.log('Node app start at port 9093')
})
